package cc.ufinity.networkdiagnose.view;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.ImageView;
import android.widget.Toast;
import cc.ufinity.networkdiagnose.app.GlobalApp;
import cc.ufinity.networkdiagnose.manager.MessageWhat;
import cc.ufinity.networkdiagnose.manager.Task;
import cc.ufinity.networkdiagnose.manager.TelManager;
import cc.ufinity.networkdiagnose.manager.WifiEAPManager;
import cc.ufinity.networkdiagnose.widget.SelectNetType_main;
import cc.ufinity.networkdiagnose.widget.TaskResult;
import cc.ufinity.networkdiagnose.widget.TaskResultAll;
import cc.ufinity.networkdiagnose.widget.TaskResultGSM;
import cc.ufinity.networkdiagnose.widget.TaskResultTD;
import cc.ufinity.networkdiagnose.widget.TaskTestResult;
import cc.ufinity.networkdiagnose.widget.TaskTestResultAll;
import cc.ufinity.networkdiagnose.widget.TaskTestResultGSM;
import cc.ufinity.networkdiagnose.widget.TaskTestResultTD;
import cc.ufinity.networkdiagnose.widget.TaskTestResultWlan;
import cc.ufinity.networkdiagnose.widget.TestWidget_GSM;
import cc.ufinity.networkdiagnose.widget.TestWidget_TD;
import cc.ufinity.networkdiagnose.widget.TestWidget_Wlan;
import cc.ufinity.networkdiagnose.widget.Test_Task_Widget_GSM;
import cc.ufinity.networkdiagnose.widget.Test_Task_Widget_Other;
import cc.ufinity.networkdiagnose.widget.Test_Task_Widget_TD;

public class TestActivity extends AbstractActivity {

	private Handler mHandler;
	//private TestWidget tw;
	//private MoveOrOther moo;
	private SelectNetType_main snt;
	protected static final String TAG_CAMERA_FLAG="cameraflag";
    protected static final String TAG_CAMERA_FLAG_VALUE="camera_result";
    private boolean isCancel = false;
    private Task task;
    public Task getTask() {
		return task;
	}

	public void setTask(Task task) {
		this.task = task;
	}

	private final String ACTION_NAME = "camera"; 
    private final String ACTION_NAME_CANCEL = "cameraCancel"; 
	
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		mHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				switch(msg.what) {
				case 1:
					dismissExitDialog();
					exit();
					break;
				}
			}
			 
		 };
		snt = new SelectNetType_main(this);
		this.setContentView(snt);
	}  
	
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		//-----------在按下返回键的时候强制关闭ftp测试；
		simpleFTPdisconnect();
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			WifiEAPManager wEapManager = new WifiEAPManager(this);
   		 	wEapManager.removeEapConfig();
   		 
			if(GlobalApp.test_Task_Widget_Other != null) {
				GlobalApp.test_Task_Widget_Other.isTesting = false;
			}
			if(GlobalApp.test_Task_Widget_Other2!= null) {
				GlobalApp.test_Task_Widget_Other2.isTesting = false;
			}
			if(GlobalApp.test_Task_Widget_GSM != null) {
				GlobalApp.test_Task_Widget_GSM.isTesting = false;
			}
			if(GlobalApp.test_Task_Widget_TD != null) {
				GlobalApp.test_Task_Widget_TD.isTesting = false;
			}
			if(GlobalApp.test_Task_Widget_Wlan != null) {
				GlobalApp.test_Task_Widget_Wlan.isTesting = false;
			}
			if(GlobalApp.test_Task_Widget_Wlan2 != null) {
				GlobalApp.test_Task_Widget_Wlan2.isTesting = false; 
			} 
			/*if(GlobalApp.taskTestGSMWidget != null) {
				GlobalApp.taskTestGSMWidget.isTesting = false;
			}
			if(GlobalApp.taskTestTDWidget != null) {
				GlobalApp.taskTestTDWidget.isTesting = false;
			}
			if(GlobalApp.taskTestWlanWidget != null) {
				GlobalApp.taskTestWlanWidget.isTesting = false;
			}
			if(GlobalApp.taskTestWlan2Widget != null) {
				GlobalApp.taskTestWlan2Widget.isTesting = false;
			}*/
			
			/*if(GlobalApp.task_Test_Widget != null) {
				GlobalApp.task_Test_Widget.isTesting = false;
			}*/
			 
			System.err.println((Integer) this.getIntent().getSerializableExtra(MessageWhat.INDEX_TEST_WIDGET)
					+ "==============================");
			if (this.getIntent().getIntExtra(MessageWhat.INDEX_SelectNetType_main_WIDGET, 0) == 1) {
				/*AlertDialog.Builder builder = new AlertDialog.Builder(this);
				builder.setTitle("提示");
				// builder.setIcon(R.drawable.what);
				builder.setMessage("确定退出系统吗？");
				builder.setCancelable(false);
				builder.setPositiveButton("确定",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								webLogout(mHandler);
								dialog.dismiss();
								showExitDialog();
							}
						});
				builder.setNegativeButton("取消",
						new DialogInterface.OnClickListener() {
							public void onClick(DialogInterface dialog, int id) {
								dialog.cancel();
							}
						});
				builder.show();*/
				this.finish();
			} else if (this.getIntent().getIntExtra(MessageWhat.INDEX_TEST_WIDGET, 0) == 1
					||this.getIntent().getIntExtra(MessageWhat.INDEX_TestWidget_TD_WIDGET, 0) == 1
					||this.getIntent().getIntExtra(MessageWhat.INDEX_TestWidget_GSM_WIDGET, 0) == 1
					||this.getIntent().getIntExtra(MessageWhat.INDEX_TestWidget_Wlan_WIDGET, 0) == 1) {
				System.out.println("【 1 】");
				setContentView(new SelectNetType_main(this));
			} else if (this.getIntent().getIntExtra(MessageWhat.INDEX_TaskResultTD_WIDGET, 0) == 1) {
				System.out.println("【 3 】");
				simpleFTPdisconnect();
				setContentView(new TestWidget_TD(this));
			} else if (this.getIntent().getIntExtra(MessageWhat.INDEX_TaskResultGSM_WIDGET, 0) == 1) {
				System.out.println("【 4 】");
				simpleFTPdisconnect();
				setContentView(new TestWidget_GSM(this));
			} else if (this.getIntent().getIntExtra(MessageWhat.INDEX_MOVEOROTHER_WIDGET, 0) == 1) {
				System.out.println("【 5】");
				simpleFTPdisconnect();
				setContentView(new TestWidget_Wlan(this));
			} else if (this.getIntent().getIntExtra(MessageWhat.INDEX_TaskResultWlan_WIDGET, 0) == 1
					|| this.getIntent().getIntExtra(MessageWhat.INDEX_TaskResultAll_WIDGET, 0) == 1) {
				System.out.println("【 6 】");
				setContentView(new SelectNetType_main(this));
			} else if (this.getIntent().getIntExtra(MessageWhat.INDEX_RssiWidget_WIDGET, 0) == 1
					|| this.getIntent().getIntExtra(MessageWhat.INDEX_PingWidget_WIDGET, 0) == 1
					|| this.getIntent().getIntExtra(MessageWhat.INDEX_FtpTestWidget_WIDGET, 0) == 1
					|| this.getIntent().getIntExtra(MessageWhat.INDEX_HttpTestWidget_WIDGET, 0) == 1
					|| this.getIntent().getIntExtra(MessageWhat.INDEX_WifiSnrTestWidget_WIDGET, 0) == 1
					|| this.getIntent().getIntExtra(MessageWhat.INDEX_TD_GSM_RssiWidget_WIDGET, 0) == 1
					|| this.getIntent().getIntExtra(MessageWhat.INDEX_TD_GSM_WifiSnrTestWidget_WIDGET, 0) == 1
					|| this.getIntent().getIntExtra(MessageWhat.INDEX_ApRelevanceTestWidget_WIDGET, 0) == 1
					|| this.getIntent().getIntExtra(MessageWhat.INDEX_SegregateTestWidget_WIDGET, 0) == 1
					|| this.getIntent().getIntExtra(MessageWhat.INDEX_RoamTestWidget_WIDGET, 0) == 1
					|| this.getIntent().getIntExtra(MessageWhat.INDEX_WebauthTestWidget_WIDGET, 0) == 1
					|| this.getIntent().getIntExtra(MessageWhat.INDEX_PeapWidget_WIDGET, 0) == 1
					|| this.getIntent().getIntExtra(MessageWhat.LFTPDOWNLOAD, 0) == 1) {
				System.out.println("【 7 】");
				simpleFTPdisconnect();
				switch(GlobalApp.nowNetType) {
				case 1:
					setContentView(new TestWidget_Wlan(this));
					break;
				case 2:
					setContentView(new TestWidget_TD(this));
					break;
				case 3:
					setContentView(new TestWidget_GSM(this));
					break;
				default:
					break;
				}
			} else if (this.getIntent().getIntExtra(MessageWhat.CameraWidget, 0) == 1) {
			 	getIntent().putExtra(TAG_CAMERA_FLAG, TAG_CAMERA_FLAG_VALUE);
				String who_to_CameraWidget = GlobalApp.who_to_CameraWidget;
            	who_to_CameraWidget = who_to_CameraWidget==null? "":who_to_CameraWidget;
            	if(who_to_CameraWidget.equals(MessageWhat.TaskResult)) {
            		setContentView(new TaskResult(this));
            		
            	} else if(who_to_CameraWidget.equals(MessageWhat.TaskResultAll)) {
            		setContentView(new TaskResultAll(this));
            		
            	} else if(who_to_CameraWidget.equals(MessageWhat.TaskResultGSM)) {
            		setContentView(new TaskResultGSM(this));
            		
            	} else if(who_to_CameraWidget.equals(MessageWhat.TaskResultTD)) {
            		setContentView(new TaskResultTD(this));
            		
            	} else if(who_to_CameraWidget.equals(MessageWhat.TaskTestResult)) {
            		setContentView(new TaskTestResult(this));
            		
            	} else if(who_to_CameraWidget.equals(MessageWhat.TaskTestResultAll)) {
            		setContentView(new TaskTestResultAll(this));
            		
            	} else if(who_to_CameraWidget.equals(MessageWhat.TaskTestResultGSM)) {
            		setContentView(new TaskTestResultGSM(this));
            		
            	} else if(who_to_CameraWidget.equals(MessageWhat.TaskTestResultTD)) {
            		setContentView(new TaskTestResultTD(this));
            		
            	} else if(who_to_CameraWidget.equals(MessageWhat.TaskTestResultWlan)) {
            		setContentView(new TaskTestResultWlan(this));
            		
            	} else if(who_to_CameraWidget.equals("")) {
            		System.out.println("--------- 1   拍照界面返回错误");
            		
            	} else {
            		System.out.println("--------- 2   拍照界面返回错误");
            	}
			} else {
				System.out.println("【 2 】");
				System.out.println((Integer) this.getIntent().getSerializableExtra(
						MessageWhat.INDEX_SelectNetType_main_WIDGET));
				setContentView(new SelectNetType_main(this));
			}
			return true;
		}  
		return false;
	}

	private void simpleFTPdisconnect() {
		new Thread() {
			public void run() {
				try {
					GlobalApp.simpleFtp.disconnect();
					GlobalApp.simpleFtp.setStop(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}.start();
	}
	@Override
	protected void onResume() {
		GlobalApp.setTestType(1);
		if(GlobalApp.isWlanTO_TD_GSM) {
			System.out.println("     ======1======          ========1====== ");
		}
		super.onResume();
	}
	
	@Override
	protected void onPostResume() {
		GlobalApp.setTestType(1);

		if(GlobalApp.isWlanTO_TD_GSM) {

			TelManager tm = new TelManager(this);
			int gsm = this.getIntent().getIntExtra(MessageWhat.INDEX_Test_Task_Widget_GSM_WIDGET, 0);
			int td = this.getIntent().getIntExtra(MessageWhat.INDEX_Test_Task_Widget_TD_WIDGET, 0);
			System.out.println(td + "     ======2======     " + gsm + "     ========2====== " + tm.getNetworkType());
			if (gsm == 1) {
				if(isCancel) {
					isCancel = false;
					GlobalApp.isWlanTO_TD_GSM = false;
					if(GlobalApp.taskOtherList.size() > 0) {
						setContentView(new Test_Task_Widget_Other(this));
					} else {
						setContentView(new TaskResultAll(this));
					}
				} else {
					if(tm.getNetworkType()!=null && (tm.getNetworkType().equals("EDGE") || tm.getNetworkType().equals("GPRS"))) {
						showAlertDialog("当前网络类型为GSM模式，进行TD测试请先切换至TD网络类型.");
					} else {
						GlobalApp.isWlanTO_TD_GSM = false;
						setContentView(new Test_Task_Widget_TD(this)); //直接跳转到TD网络测试
					}
				}
				
			} else if(td == 1) {
				if(isCancel) {
					isCancel = false;
					GlobalApp.isWlanTO_TD_GSM = false;
					if(GlobalApp.taskOtherList.size() > 0) {
						setContentView(new Test_Task_Widget_Other(this));
					} else {
						setContentView(new TaskResultAll(this));
					}
				} else {
					if(tm.getNetworkType()!=null && (tm.getNetworkType().equals("HSDPA")) || tm.getNetworkType().equals("HSUPA")){
						showAlertDialog("当前网络类型为TD模式，进行TD测试请先切换至GSM网络类型.");
					} else {
						GlobalApp.isWlanTO_TD_GSM = false;
						setContentView(new Test_Task_Widget_GSM(this)); //直接跳转到GSM网络测试
					}
				}
				
			}
		}
		
		
		super.onPostResume();
	}
	
	
	
	public void showAlertDialog(final String message) { 
        AlertDialog.Builder builder = new AlertDialog.Builder(this); 
    	builder.setTitle("测试提示");   
    	builder.setMessage(message); 
    	builder.setCancelable(false);
 		builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
 			public void onClick(DialogInterface dialog, int id) { 
 				try {
 					Intent intent = new Intent(Intent.ACTION_MAIN);
 					intent.setClassName("com.android.phone", "com.android.phone.NetworkSetting");
 					startActivity(intent);
 				} catch (Exception e) {
 					showAlertDialog(message);
 					Toast.makeText(TestActivity.this, "该手机不支持TD/GSM网络切换", Toast.LENGTH_LONG).show();
 				}
 			}
 		}); 
 		builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
 			public void onClick(DialogInterface dialog, int id) {
 				isCancel = true;
 				GlobalApp.isWlanTO_TD_GSM = false;
				if(GlobalApp.taskOtherList.size() > 0) {
					setContentView(new Test_Task_Widget_Other(TestActivity.this));
				} else {
					setContentView(new TaskResultAll(TestActivity.this));
				}
        		dialog.cancel();
 			}
 		});
 		
 		builder.create().show();
    }
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == Activity.RESULT_OK) {
			String sdStatus = Environment.getExternalStorageState();
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) { 
				Log.v("TestFile",
						"SD card is not avaiable/writeable right now.");
				Toast.makeText(this, "请插入SD卡", Toast.LENGTH_LONG).show();
				return;
			}
			Bundle bundle = data.getExtras();
			Bitmap bitmap = (Bitmap) bundle.get("data");// 
			FileOutputStream b = null;
			File fileDir1 = this.getFilesDir();
	        String path = fileDir1.getParent()+ File.separator + "wlantest" + File.separator;
	        File fileDir2 = new File(path); 
	        fileDir2.mkdir();
			String fileName = path+"temp.jpg"  ;
			System.out.println("fileName:"+fileName);
			try {
				b = new FileOutputStream(fileName);
				bitmap.compress(Bitmap.CompressFormat.JPEG, 100, b); 
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} finally {
				try {
					b.flush();
					b.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			 Intent mIntent = new Intent(ACTION_NAME); 
             mIntent.putExtra("fileName", "temp.jpg"); 
              
             //发送广播 
             sendBroadcast(mIntent); 
             System.out.println("发送广播");
		//	((ImageView) findViewById(R.id.imageView)).setImageBitmap(bitmap);// ��ͼƬ��ʾ��ImageView��
		}else{
			Intent mIntent = new Intent(ACTION_NAME_CANCEL); 
             
            //发送广播 
            sendBroadcast(mIntent); 
            System.out.println("相机取消发送广播");
		}
	}

	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		System.out.println("--------------testactivity---------------------pause------------");
		super.onPause();
	} 
	
}
